package com.chatmusicstatus.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import org.jivesoftware.smack.XMPPException;

public class MusicStatusReceiver extends BroadcastReceiver{

    private class TimeoutHandler extends Handler {

        public TimeoutHandler() {
            
        }
        @Override
        public void handleMessage(Message msg) {
            MusicStatusReceiver.this.caller.stopSelf();
        }

        public void sleep(long delayMillis) {
            this.removeMessages(0);
            sendMessageDelayed(obtainMessage(0), delayMillis);
        }
        public void clear() {
            this.removeMessages(0);
        }
    }
    
    private XMPPStatusSetter[] msgSetter;

    private enum initState { STARTED, METARECEIVED, INITIALIZED };
    private enum musicState { PLAYING,STOPPED };
    
    private initState objInitState;
    private musicState objMusicState;
    private long currentID;
    private static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
    private static final String META_CHANGED = "com.android.music.metachanged";
    private static final String PLAYBACK_COMPLETE = "com.android.music.playbackcomplete";
    private int acc_count;
    
    private TimeoutHandler pauseTimeoutHandler;
    private int pause_timeout;
    public MusicStatusService caller;
    
    MusicStatusReceiver(Cursor c, MusicStatusService s) throws XMPPException {
        objInitState = initState.STARTED;
        objMusicState = musicState.STOPPED;
        currentID=-1;
        caller = s;
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(s.getApplicationContext());
        pause_timeout = Integer.valueOf(pref.getString("pause_timeout", "0")) * 60000;
        pauseTimeoutHandler = new TimeoutHandler();
        acc_count = c.getCount();
        msgSetter = new XMPPStatusSetter[acc_count];
        int i=0;
        while(c.moveToNext())
        {
            msgSetter[i]=new XMPPStatusSetter(c.getString(0), c.getInt(1), c.getString(6), c.getString(2), c.getString(3));
            i++;
        }
        c.close();
    }

    @Override
    public void onReceive(Context cntxt, Intent intent) {
        String action = intent.getAction();
        if(META_CHANGED.equals(action))
            metaChanged(intent);
        else if(PLAYSTATE_CHANGED.equals(action))
            playstateChanged(intent);
        else if(PLAYBACK_COMPLETE.equals(action))
            playbackComplete(intent);
    }
    
    void stopReceive() {
        for(int i=0;i<acc_count;i++) {
            msgSetter[i].Close();
        }
    }
    
    private void metaChanged(Intent intent) {
        String artist = intent.getStringExtra("artist");
        String album = intent.getStringExtra("album");
        String track = intent.getStringExtra("track");
        Long id = intent.getLongExtra("id", -1);
        switch(objInitState)
        {
            case STARTED:
                currentID=id;
                objInitState=initState.METARECEIVED;
                break;
            case METARECEIVED:
                //cant be here, log error
                break;
            case INITIALIZED:
                //if received on current song do nothing
                //if received on another song, set state to playing, update initID
                if(id!=currentID)
                {
                    objMusicState=musicState.PLAYING;
                    currentID=id;
                    for(int i=0;i<acc_count;i++){
                        if(!msgSetter[i].setStatus("\u266B Now Playing:\""+track+"\" by \""+artist+"\" on Android"));//log error
                    }
                    pauseTimeoutHandler.clear();
                }
                break;  
        }
    }

    private void playstateChanged(Intent intent) {
        String artist = intent.getStringExtra("artist");
        //String album = intent.getStringExtra("album");
        String track = intent.getStringExtra("track");
        Long id = intent.getLongExtra("id", -1);
        switch(objInitState)
        {
            case STARTED:
                //cant be here, log error
                break;
            case METARECEIVED:
                if(id==currentID)
                    objInitState= initState.INITIALIZED;
                break;
            case INITIALIZED:
                //if received on the currnet song, toggle state
                if(id==currentID)
                {
                    switch(objMusicState)
                    {
                        case PLAYING:
                            objMusicState= musicState.STOPPED;
                            //unset Gtalk status here
                            for(int i=0;i<acc_count;i++) {
                                if(!msgSetter[i].setStatus(""));//log error
                            }
                            startPauseTimeOut();
                            break;
                        case STOPPED:
                            objMusicState= musicState.PLAYING;
                            for(int i=0;i<acc_count;i++) {
                                if(!msgSetter[i].setStatus("\u266B Now Playing:\""+track+"\" by \""+artist+"\" on Android"));//log error
                            }
                            pauseTimeoutHandler.clear();
                            break;
                    }
                }
                //if reveived on new song, set state to playing, update initID
                else
                {
                    objMusicState=musicState.PLAYING;
                    currentID=id;
                    for(int i=0;i<acc_count;i++) {
                        if(!msgSetter[i].setStatus("\u266B Now Playing:\""+track+"\" by \""+artist+"\" on Android"));//log error
                    }
                    pauseTimeoutHandler.clear();
                }
                break;  
        }
    }

    private void playbackComplete(Intent intent) {
        if(objInitState==initState.INITIALIZED)
        {
            objMusicState=musicState.STOPPED;
            for(int i=0;i<acc_count;i++) {
                if(!msgSetter[i].setStatus(""));//log error
            }
            startPauseTimeOut();
        }
    }
    private void startPauseTimeOut()
    {
        if(pause_timeout!=0)
            pauseTimeoutHandler.sleep(pause_timeout);
    }
}
